
// pages/DetailsRedPackets/detailsRedPackets.js
const app = getApp()
// var base64 = require('../../utils/base64.js')
const CryptoJS = require('../../utils/aes-jia.js');
var timestamp = Date.parse(new Date()) / 1000; 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    redId:'',
    item:{},
    show:false,
    amountRedEnvelope: '',
    amountRedEnvelopeico:'',
    givingAdvice:'',
    isOver: true,
    walletBalance:'',
    user:{},
    showPopup:false,
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    prepaymentRecordId: '',
    whetherSetPayPwd:'',
  },


  returnCeremonySelection:function(e) {
    var that = this;
    if (that.data.amountRedEnvelope == 0 || that.data.amountRedEnvelope.length == 0) {
      wx.showToast({
        title: "请输入回礼金额",
        icon: 'none',
        duration: 2000
      })
      return
    } 
    // else if (that.data.amountRedEnvelope > that.data.item.redPacket){
    //   wx.showToast({
    //     title: "输入金额不可超过" + that.data.item.sendName+"给您发的红包金额",
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    else{
      that.setData({
        showPopup: true,
        show: false
      })
    }
  },

  removePopContent:function(e) {
    this.setData({
      showPopup: false
    })
  },

  returnCeremony:function (e) {
    this.setData ({
      show:true
    })
  },
  returnfocus(e){
    this.setData({
      amountRedEnvelopeico:''
    })
  },
  //输入金额
  amountInput: function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    console.log('bug1')
    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      console.log('bug2')
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      console.log('bug3')
      e.detail.value = 500000
    }
    this.setData({
      amountRedEnvelope: e.detail.value,
    })
    
  },
  amountblur(e){
    if (e.detail.value !==''){
      this.setData({
        amountRedEnvelopeico:'￥'+this.data.amountRedEnvelope
      })
    }
  },

  givingAdviceInput:function(e) {
    this.setData({
      givingAdvice: e.detail.value.replace(/\s+/g, '')
    })
  },

  xClosetwo:function (e) {
    this.setData({
      show: false,
      givingAdvice:'',
      amountRedEnvelope:''
    })
  },

  reddetails:function (e) {
    var that = this
    app.req({
      url: "wechat/birthManagePart/info",
      method: "post",
      data: {
        id: that.data.redId
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("红包详情", res)
          var time = res.data.openTime
          res.data.openTime = time.substring(11,16)
          that.setData({
            item:res.data
          })
        }
      }
    })
  },
  //支付
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.walletBalance < that.data.amountRedEnvelope) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd) {
          that.setData({
            showPayPwdInput: true,
            payFocus:true
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.navigateTo({
                  url: '/pages/password/password',
                })
              }
            }
          })
        }
      }
    }
  },
  addToActivity: function (e) {
    var that = this;
    var payWay = '';
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    var blessings = (that.data.givingAdvice == '' ? '万分感谢，小小心意，请笑纳' : that.data.givingAdvice)
    if (e == 0) {
      payWay = 0
    } else {
      payWay = e.currentTarget.dataset.id;
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      var userId = that.data.user.id
      console.log("支付方式", payWay,app.url)
      wx.request({
        url: app.globalData.url+ "wechat/birthManagePart/returnSalute?uid=" + that.data.user.id + '&prepaymentRecordId=' + that.data.prepaymentRecordId,
        method: "post",
        header: {
          'api-client': '8693ece21a2711ea995200163e05ff66',
          'api-version': '1.3.1',
        },
        showLoad: true,
        data: {
          birthId: that.data.item.birthId,
          sendId: userId,
          blessingType: 4,
          blessings: blessings,
          redPacket: that.data.amountRedEnvelope,
          relationId: that.data.item.relationId,
          payWay: payWay,
          id:that.data.item.id,
          // prepaymentRecordId: that.data.prepaymentRecordId,
        },
        success: function (res) {
          console.log("支付", that.data.amountRedEnvelope,res)
          if (res.data.code == 200 && payWay == 0) {
            that.setData({
              showPopup: false,
              isOver: true
            })
            wx.navigateBack({
              delta: 1
            })
            wx.showToast({
              title: "红包已回赠",
              duration: 2000
            })
          } else if (res.data.code == 200 && payWay == 1) {
            var paydata = res.data.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  showPopup: false,
                  isOver: true
                })
                wx.navigateBack({
                  delta: 1
                })
                wx.showToast({
                  title: "红包已回赠",
                  duration: 2000
                })
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.data.errMsg)
              }
            })
          } else {
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },


  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    let data = {
      "pageNumber": 1,
      "pageSize": 10
    }
    app.req({
      url: "wechat/account/expenseCalendars",
      method: "post",
      data: data,
      success: function (res) {
        console.log('获取钱包余额',res)
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //预支付
  operationRecord() {
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "wechat/wxpay/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: ''
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: ''
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {
    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    } 
  },
  // pswdBtn() {
  //   if (this.data.pwdVal.length >= 6) {
  //     this.setData({
  //       showPayPwdInput: false,
  //       payFocus: false
  //     });
  //     this.operationRecord()
  //   } else {
  //     wx.showToast({
  //       title: "请输入密码",
  //       icon: 'none',
  //       duration: 2000
  //     })
  //   }
  // },

  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'wechat/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      redId: options.redId,
    })
    
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo
      })
      that.reddetails()
      that.getWalletBalance()
    })
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})